package com.awesome.core;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import lombok.extern.slf4j.Slf4j;

/**
 * clone from mybatis-plus website : https://baomidou.com/guide/generator.html
 * 
 * @author : HongKai.wang
 * @date : 2019/5/21
 */
@Slf4j
public class MybatisPlusGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in, "UTF-8");
        log.info("请输入" + tip + "：");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * RUN THIS
     */
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        /* ------------------------可改动的地方------------------------ */
        // 项目输出目录
        String projectParentPath = System.getProperty("user.dir");
        // 项目名称
        String projectName = "awesome-scaffold";
        String codeAuthor = "Hongkai.Wang";
        String jdbcDriver = "com.mysql.jdbc.Driver";
        String jdbcUrl =
            "jdbc:mysql://127.0.0.1:3306/awesome_scaffold?useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&generateSimpleParameterMetadata=true";
        String jdbcUserName = "root";
        String jdbcPsw = "123456";

        String baseCodePackage = "com.awesome";
        /* ------------------------可改动的地方------------------------ */
        // 项目全路径
        String projectPath = projectParentPath + File.separator + projectName;
        String javaOutputDir = projectPath + "/src/main/java";
        String mapperOutputDir = projectPath + "/src/main/resources/mapper/";
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(javaOutputDir);
        gc.setAuthor(codeAuthor);
        gc.setOpen(true);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(jdbcUrl);
        dsc.setDriverName(jdbcDriver);
        dsc.setUsername(jdbcUserName);
        dsc.setPassword(jdbcPsw);
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("代码模块名"));
        pc.setParent(baseCodePackage);
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // Tips: 可以过滤不要生成的字段
                // 自定义输入文件名称
                return mapperOutputDir + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper"
                    + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 自定义输出模板
        mpg.setTemplate(new TemplateConfig().setXml(null).setEntity("/templates/self_entity.java"));
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setInclude(scanner("表名"));
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
